package BaseService

import (
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/util/gconv"
	"seawolf-admin-go/internal/request/BaseReq"
	"seawolf-admin-go/utility/db"
	"seawolf-admin-go/utility/response"
	"time"
)

func Delete(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	if req.Ids == nil || len(req.Ids) == 0 {
		return response.FailByRequestMessage(nil, "参数错误 ids 不能为空")
	}
	ctx := r.GetCtx()
	data := g.Map{
		"delete_at": time.Now().Unix(),
	}
	// 编辑前方法
	if req.DeleteBeforeFn != nil {
		respRes := req.DeleteBeforeFn(r, data)
		if respRes.Code != 0 {
			return respRes
		}
	}
	obj := db.GetUnSafaTable(ctx, req.TableName).Where(
		"id",
		gconv.SliceAny(req.Ids),
	)
	// 判断是否软删除
	if len(req.SoftDeleteField) > 0 {
		// 软删除
		_, err := obj.Update(data)
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
	} else {
		// 真实删除
		_, err := obj.Delete()
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
	}
	// 删除成功，尝试删除缓存
	HandleBaseCache(ctx, req.TableName)
	result := g.Map{
		"ids": gconv.SliceAny(req.Ids),
	}
	// 后置方法
	if req.DeleteAfterFn != nil {
		respRes := req.DeleteAfterFn(r, data, result)
		if respRes.Code != 0 {
			return respRes
		}
	}
	return response.SuccessByRequestMessageData(nil, "删除成功", result)
}
